package com.lf2.tool;



import android.annotation.SuppressLint;

import com.lf2.Lf_Debug;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.regex.Pattern;


public class StringUtil
{
    public StringUtil() {}

    public static byte charToByte(char c)
    {
        return (byte)"0123456789ABCDEF".indexOf(c);
    }
    //iso-8859-1
    //gbk
    //utf-16
    //utf-8
    public static byte[] get_isobyte(String isostring)
    {
        byte[] iso;
        try {
            iso = isostring.getBytes("iso-8859-1");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Lf_Debug.e_printf(Lf_Debug._FILE_LINE_FUNC_(), e);
            iso = isostring.getBytes();
        }
        return iso;
    }

    public static String get_isostring(byte[] iso)
    {
        String isostring;
        try {
            isostring = new String(iso, "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Lf_Debug.e_printf(Lf_Debug._FILE_LINE_FUNC_(), e);
            isostring = new String(iso);
        }
        return isostring;
    }

    public static byte[] get_gbkbyte(String gbkstring)
    {
        byte[] gbk;
        try {
            gbk = gbkstring.getBytes("GBK");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Lf_Debug.e_printf(Lf_Debug._FILE_LINE_FUNC_(), e);
            gbk = gbkstring.getBytes();
        }
        return gbk;
    }

    public static String get_gbkstring(byte[] gbk)
    {
        String gbkstring;
        try {
            gbkstring = new String(gbk, "GBK");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Lf_Debug.e_printf(Lf_Debug._FILE_LINE_FUNC_(), e);
            gbkstring = new String(gbk);
        }
        return gbkstring;
    }

    public static String formatTransAmount(String data)
    {
        int index = data.indexOf(".");
        if (index == -1)
        {
            data = data + ".00";
        }
        else if (data.substring(index + 1).length() == 1)
        {
            data = data + "0";
        }
        return data;
    }

    public static String formatTransAmountToFen(String data)
    {
        String str = new String();
        String preStr = new String();
        int index = data.indexOf(".");
        int value = -1;
        if (index == -1)
        {
            data = data + ".00";
            value = data.indexOf(".");
            str = data.substring(0, value) + data.substring(value + 1);
        }
        else
        {
            if (data.substring(index + 1).length() == 1)
            {
                data = data + "0";
            }
            str = data.substring(0, index) + data.substring(index + 1);
        }
        for (int i = 0; i < 12 - str.length(); i++)
        {
            preStr = preStr + "0";
        }
        str = preStr + str;
        return str;
    }

    @SuppressLint("DefaultLocale")
    public static String hexStringToChars(String hexString)
    {
        if ((hexString == null) || (hexString.equals(""))) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        StringBuffer sb = new StringBuffer();
        byte d = 0;
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[(pos + 1)]));
            sb.append((char)d);
        }
        return sb.toString();
    }

    public static String decodeUnicode(String theString)
    {
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;)
        {
            char aChar = theString.charAt(x++);
            if (aChar == '\\')
            {
                aChar = theString.charAt(x++);
                if (aChar == 'u')
                {
                    int value = 0;
                    for (int i = 0; i < 4; i++)
                    {
                        aChar = theString.charAt(x++);
                        switch (aChar)
                        {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - 48;
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 97;
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 65;
                                break;
                            case ':':
                            case ';':
                            case '<':
                            case '=':
                            case '>':
                            case '?':
                            case '@':
                            case 'G':
                            case 'H':
                            case 'I':
                            case 'J':
                            case 'K':
                            case 'L':
                            case 'M':
                            case 'N':
                            case 'O':
                            case 'P':
                            case 'Q':
                            case 'R':
                            case 'S':
                            case 'T':
                            case 'U':
                            case 'V':
                            case 'W':
                            case 'X':
                            case 'Y':
                            case 'Z':
                            case '[':
                            case '\\':
                            case ']':
                            case '^':
                            case '_':
                            case '`':
                            default:
                                throw new IllegalArgumentException("Malformed encoding.");
                        }
                    }
                    outBuffer.append((char)value);
                }
                else
                {
                    if (aChar == 't')
                    {
                        aChar = '\t';
                    }
                    else if (aChar == 'r')
                    {
                        aChar = '\r';
                    }
                    else if (aChar == 'n')
                    {
                        aChar = '\n';
                    }
                    else if (aChar == 'f')
                    {
                        aChar = '\f';
                    }
                    outBuffer.append(aChar);
                }
            }
            else
            {
                outBuffer.append(aChar);
            }
        }
        return outBuffer.toString();
    }

    public static String intToHexString(int i, int length) {
        String a = Integer.toHexString(i);
        for (int j = a.length(); j < length * 2; j++) {
            a = "0" + a;
        }
        return a;
    }

    public static byte[] charsToBytes(char[] chars) {
        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(chars.length);
        cb.put(chars);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);
        return bb.array();
    }

    public static char[] bytesToChars(byte[] bytes) {
        Charset cs = Charset.forName("UTF-8");
        ByteBuffer bb = ByteBuffer.allocate(bytes.length);
        bb.put(bytes);
        bb.flip();
        CharBuffer cb = cs.decode(bb);
        return cb.array();
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p =
                Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        java.util.regex.Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static String getHiddenCardNo(String cardNo)
    {
        try
        {
            return cardNo.substring(0, 6) + "*********".substring(19 - cardNo.length()) + cardNo.substring(cardNo.length() - 4);
        }
        catch (Exception e) {
            e.printStackTrace();
            Lf_Debug.e_printf(Lf_Debug._FILE_LINE_FUNC_(), e);
        }
        return "";
    }

    public static String getFormatAmount(String amount)
    {
        int mAmount = (int)(Double.parseDouble(amount) * 100.0D);
        return String.format("%012d", mAmount);
    }

    @SuppressLint("DefaultLocale")
    public static String getFromatAmount(int amount)
    {
        String mAmount = String.format("%012d", new Object[] { Integer.valueOf(amount) });
        return mAmount.substring(mAmount.length() - 12, mAmount.length());
    }

    public static String getQrcodeAmount(String amount)
    {
        int mAmount = (int)(Double.parseDouble(amount) * 100.0D);
        return String.valueOf(mAmount);
    }

    public static String getReadableAmount(String amount)
    {
        if ((amount == null) || (amount.isEmpty())) {
            return "0.00";
        }
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(Double.parseDouble(amount) / 100.0D);
    }

    public static String getReadableAmount(double amount)
    {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(amount);
    }

    public static int getStringLength(String str)
    {
        try
        {
            byte[] b = str.getBytes("gb2312");
            return b.length;
        }
        catch (Exception ex)
        {

        }
        return 0;
    }

    public static boolean containChinese(String str)
    {
        if ((str != null) &&
                (getStringLength(str) > str.length()))
        {
            return true;
        }
        return false;
    }

    public static String getSubChineseString(String src, int start, int engLen)
    {
        int len = src.length();
        String subString = src.substring(start, start + len);
        if (getStringLength(subString) > engLen)
        {
            subString = src.substring(start, start + len / 2);
        }
        else
        {
            return subString;
        }

        if ((getStringLength(subString) == engLen) ||
                ((getStringLength(subString) + 1 == engLen)
                        && (src.length() > subString.length())
                        && (getStringLength(src.substring(subString.length(), subString.length() + 1)) > 1)))
        {
            return subString;
        }
        if (getStringLength(subString) > engLen) {
            return getSubChineseString(subString, 0, engLen);
        }
        String cutOutString = src.substring(start + len / 2, start + len);
        return subString + getSubChineseString(cutOutString, 0, engLen - getStringLength(subString));
    }

    public static String appendPadding(String str, String padding, int length, String leftOrRight)
    {
        if (str == null) {
            str = "";
        }
        int originalLength = str.length();
        if ("L".equalsIgnoreCase(leftOrRight))
        {
            for (int i = 0; i < length - originalLength; i++) {
                str = padding + str;
            }
        }
        else
        {
            for (int i = 0; i < length - originalLength; i++) {
                str = str + padding;
            }
        }

        return str;
    }

    public static String ToSBC(String input)
    {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i] == ' ')
            {
                c[i] = '　';
            }
            else if (c[i] < '')
            {
                c[i] = ((char)(c[i] + 65248));
            }
        }
        return new String(c);
    }

    public static String ToDBC(String input)
    {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i] == '　')
            {
                c[i] = ' ';
            }
            else if ((c[i] > 65280) && (c[i] < 65375))
            {
                c[i] = ((char)(c[i] - 65248));
            }
        }
        String returnString = new String(c);
        return returnString;
    }

    public static String mask(String value, String mask)
    {
        int markStart = -1;
        for (int i = 0; i < mask.length(); i++)
        {
            if (mask.charAt(i) == '*') {
                markStart = i;
                break;
            }
            if ((mask.charAt(i) != 'x') && (mask.charAt(i) != 'X')) {
                markStart = i;
                break;
            }
        }

        if ((markStart == -1) || (markStart >= value.length())) {
            return value;
        }

        int markEnd = markStart + 1;
        for (int i = mask.length() - 1; i > markStart + 1; i--) {
            if (mask.charAt(i) == '*') {
                markEnd = i + 1;
                break;
            }
            if ((mask.charAt(i) != 'x') && (mask.charAt(i) != 'X')) {
                markEnd = i + 1;
                break;
            }
        }

        if (mask.length() - markEnd + markStart >= value.length()) {
            return value;
        }

        StringBuilder str = new StringBuilder();
        str.append(value.substring(0, markStart));

        markEnd += value.length() - mask.length();

        for (int i = markStart; i < markEnd; i++) {
            str.append("*");
        }

        if (markEnd < value.length()) {
            str.append(value.substring(markEnd));
        }

        return str.toString();
    }

    public static String formatString(String value, String formatString, boolean isLeftDirection)
    {
        StringBuilder result = new StringBuilder();
        if (isLeftDirection)
        {
            int i = 0;int n = 0;
            do {
                char cur = formatString.charAt(i);
                if ((cur == 'x') || (cur == 'X'))
                {
                    result.append(value.charAt(n));
                    n++;
                }
                else
                {
                    result.append(cur);
                }
                i++;
                if (i >= formatString.length())
                    break;
            } while (n < value.length());
        }
        else
        {
            int i = formatString.length() - 1;
            for (int n = value.length() - 1; (i >= 0) && (n >= 0); i--)
            {
                char cur = formatString.charAt(i);
                if ((cur == 'x') || (cur == 'X'))
                {
                    result.insert(0, value.charAt(n));
                    n--;
                }
                else
                {
                    result.insert(0, cur);
                }
            }
        }
        return result.toString();
    }

    public static String getFileAddSpace(String replace) {
        String regex = "(.{2})";
        replace = replace.replaceAll(regex, "$1 ");
        return replace;
    }
}
